package com.akkainaction.helloactor.life.actor;

import akka.actor.*;
import akka.event.Logging;
import akka.event.LoggingAdapter;

public class WatchActor2 extends UntypedActor {

    LoggingAdapter log = Logging.getLogger(this.getContext().system(), this);

    ActorRef child = null;

    @Override
    public void preStart() throws Exception {
        log.info("WatchActor preStart");
        child = getContext().actorOf(Props.create(WorkerActor.class), "workerActor");
        //对childActor进行监控
        getContext().watch(child);
    }

    @Override
    public void postStop() throws Exception {
        log.info("WatchActor postStop");
    }

    @Override
    public void onReceive(Object msg) throws Exception {
        log.info("WatchActor收到消息：" + msg);
        if (msg instanceof String) {
            if ("stopWorker".equals(msg)) {
                log.info("收到消息:[" + msg + "],开始停止:[" + child.path() + "]");
                child.tell(Kill.getInstance(), getSelf());
            }
        } else if (msg instanceof Terminated) {
            Terminated t = (Terminated) msg;
            log.info("监控到:[" + t.getActor() + "]停止了");
        } else {
            unhandled(msg);
        }
    }
}
